<template>
  <div class="analysis-page">
    <!-- 页面标题与操作区 -->
    <div class="page-header">
      <el-page-header :content="['质检管理', '统计分析']" />
      <el-dropdown trigger="click" placement="bottom">
        <el-button type="success" icon="el-icon-download">导出数据</el-button>
        <el-dropdown-menu>
          <el-dropdown-item @click="handleExport('current')">导出当前筛选数据</el-dropdown-item>
          <el-dropdown-item @click="handleExport('all')">导出全部数据</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <!-- 筛选区域 -->
    <el-card shadow="hover" class="filter-card">
      <el-form :inline="true" :model="searchForm" label-width="100px" size="medium">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 300px;"
          />
        </el-form-item>
        <el-form-item label="物料群组">
          <el-select 
            v-model="searchForm.materialGroupId" 
            placeholder="全部" 
            clearable
            style="width: 200px;"
          >
            <el-option label="全部" value="" />
            <el-option 
              v-for="group in materialGroups" 
              :key="group.id" 
              :label="group.name" 
              :value="group.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="质检状态">
          <el-select 
            v-model="searchForm.qualityStatus" 
            placeholder="全部" 
            clearable
            style="width: 180px;"
          >
            <el-option label="全部" value="" />
            <el-option label="全合格" value="allPass" />
            <el-option label="部分合格" value="partPass" />
            <el-option label="全不合格" value="allFail" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchAndAnalyzeData">查询</el-button>
          <el-button @click="resetSearch" style="margin-left: 8px;">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计概览卡片 -->
    <el-row :gutter="16" class="stat-card-group">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">总质检次数</div>
          <div class="stat-value">{{ stats.totalCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">平均合格率</div>
          <div class="stat-value" :style="{ color: getRateColor(stats.averageRate) }">
            {{ stats.averageRate.toFixed(1) }}%
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">不合格记录数</div>
          <div class="stat-value" style="color: #FF5252;">{{ stats.unqualifiedCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">不合格占比</div>
          <div class="stat-value" :style="{ color: getRateColor(100 - stats.unqualifiedRatio) }">
            {{ stats.unqualifiedRatio.toFixed(1) }}%
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="16" class="chart-group">
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header" class="chart-header">合格率趋势（按日期）</div>
          <div class="chart-container">
            <div ref="trendChartRef" class="chart-dom"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header" class="chart-header">物料群组合格率排行</div>
          <div class="chart-container">
            <div ref="groupChartRef" class="chart-dom"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="chart-header">质检人员工作量统计</div>
          <div class="chart-container">
            <div ref="workloadChartRef" class="chart-dom"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick, watch, onBeforeUnmount } from 'vue';
import axios from 'axios';
import moment from 'moment';
import * as echarts from 'echarts';
// import XLSX from 'xlsx';
// import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
import { ElMessage, ElLoading } from 'element-plus';

// 基础配置
axios.defaults.baseURL = 'http://localhost:5046';

// 图表DOM引用
const trendChartRef = ref<HTMLDivElement | null>(null);
const groupChartRef = ref<HTMLDivElement | null>(null);
const workloadChartRef = ref<HTMLDivElement | null>(null);

// 图表实例
let trendChartInstance: echarts.ECharts | null = null;
let groupChartInstance: echarts.ECharts | null = null;
let workloadChartInstance: echarts.ECharts | null = null;

// 筛选表单数据
const searchForm = reactive({
  dateRange: [] as string[],
  materialGroupId: '',
  qualityStatus: ''
});

// 统计数据
const stats = reactive({
  totalCount: 0,          // 总质检次数
  averageRate: 0,         // 平均合格率
  unqualifiedCount: 0,    // 不合格记录数
  unqualifiedRatio: 0     // 不合格记录占比
});

// 物料群组列表
const materialGroups = ref<any[]>([]);
// 原始质检数据
const rawQualityData = ref<any[]>([]);

// 根据合格率获取颜色
const getRateColor = (rate: number) => {
  if (rate >= 90) return '#4CAF50';
  if (rate >= 70) return '#8BC34A';
  if (rate >= 50) return '#FFC107';
  return '#FF5252';
};

// 重置筛选条件
const resetSearch = () => {
  searchForm.dateRange = [];
  searchForm.materialGroupId = '';
  searchForm.qualityStatus = '';
  fetchAndAnalyzeData();
};

// 初始化图表
const initCharts = () => {
  if (trendChartRef.value && !trendChartInstance) {
    trendChartInstance = echarts.init(trendChartRef.value);
  }
  if (groupChartRef.value && !groupChartInstance) {
    groupChartInstance = echarts.init(groupChartRef.value);
  }
  if (workloadChartRef.value && !workloadChartInstance) {
    workloadChartInstance = echarts.init(workloadChartRef.value);
  }
};

// 销毁图表
const destroyCharts = () => {
  if (trendChartInstance) {
    trendChartInstance.dispose();
    trendChartInstance = null;
  }
  if (groupChartInstance) {
    groupChartInstance.dispose();
    groupChartInstance = null;
  }
  if (workloadChartInstance) {
    workloadChartInstance.dispose();
    workloadChartInstance = null;
  }
};

// 获取并分析质检数据（核心方法）
const fetchAndAnalyzeData = async () => {
  const loading = ElLoading.service({ text: '数据加载中...' });
  try {
    // 调用API获取数据
    const response = await axios.get('/api/QualityInspection/QualityInspectionQuery', {
      params: {
        Index: 1,
        Size: 9999,
        materialGroupId: searchForm.materialGroupId
      }
    });

    if (response.data.code !== 200) throw new Error('获取数据失败');
    let data = response.data.data.totalPage || [];

    // 计算每条记录的合格百分比
    data = data.map((item: any) => ({
      ...item,
      qualifiedPercentage: item.inspectedQuantity 
        ? (item.qualifiedQuantity / item.inspectedQuantity) * 100 
        : 0,
      inspectionDate: moment(item.inspectionTime).format('YYYY-MM-DD')
    }));

    // 前端二次筛选
    data = data.filter((item: any) => {
      // 时间范围筛选
      if (searchForm.dateRange.length === 2) {
        const itemDate = item.inspectionDate;
        const start = searchForm.dateRange[0];
        const end = searchForm.dateRange[1];
        if (itemDate < start || itemDate > end) return false;
      }
      // 质检状态筛选
      if (searchForm.qualityStatus) {
        const isAllPass = item.qualifiedQuantity === item.inspectedQuantity;
        const isAllFail = item.qualifiedQuantity === 0;
        if (searchForm.qualityStatus === 'allPass' && !isAllPass) return false;
        if (searchForm.qualityStatus === 'allFail' && !isAllFail) return false;
        if (searchForm.qualityStatus === 'partPass' && (isAllPass || isAllFail)) return false;
      }
      return true;
    });

    // 提取物料群组列表（去重）
    const groupSet = new Set<any>();
    data.forEach((item: any) => {
      if (item.materialGroupId && item.materialGroupName) {
        groupSet.add({
          id: item.materialGroupId,
          name: item.materialGroupName
        });
      }
    });
    materialGroups.value = Array.from(groupSet);

    // 计算核心统计指标
    stats.totalCount = data.length;
    const totalRate = data.reduce((sum: number, item: any) => sum + item.qualifiedPercentage, 0);
    stats.averageRate = data.length > 0 ? totalRate / data.length : 0;
    stats.unqualifiedCount = data.filter((item: any) => item.unqualifiedQuantity > 0).length;
    stats.unqualifiedRatio = data.length > 0 ? (stats.unqualifiedCount / data.length) * 100 : 0;

    // 渲染图表
    rawQualityData.value = data;
    await nextTick();
    initCharts();
    renderTrendChart();
    renderGroupChart();
    renderWorkloadChart();

  } catch (error) {
    ElMessage.error(`统计失败: ${(error as Error).message || '未知错误'}`);
    console.error(error);
  } finally {
    loading.close();
  }
};

// 渲染合格率趋势图（按日期分组）
const renderTrendChart = () => {
  if (!trendChartInstance) return;

  const dateRateMap: Record<string, { sum: number; count: number }> = {};
  rawQualityData.value.forEach((item: any) => {
    const date = item.inspectionDate;
    if (!dateRateMap[date]) {
      dateRateMap[date] = { sum: 0, count: 0 };
    }
    dateRateMap[date].sum += item.qualifiedPercentage;
    dateRateMap[date].count += 1;
  });

  const dates = Object.keys(dateRateMap).sort();
  const rates = dates.map(date => {
    const { sum, count } = dateRateMap[date];
    return (sum / count).toFixed(1);
  });

  trendChartInstance.setOption({
    tooltip: { trigger: 'axis', formatter: '{b}: {c}%' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: dates },
    yAxis: { type: 'value', min: 0, max: 100, axisLabel: { formatter: '{value}%' } },
    series: [{
      name: '平均合格率',
      type: 'line',
      data: rates,
      smooth: true,
      itemStyle: { color: '#4096ff' },
      lineStyle: { color: '#4096ff' },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(64, 150, 255, 0.3)' },
          { offset: 1, color: 'rgba(64, 150, 255, 0)' }
        ])
      }
    }]
  });
};

// 渲染物料群组合格率排行图
const renderGroupChart = () => {
  if (!groupChartInstance) return;

  const groupRateMap: Record<string, { sum: number; count: number; name: string }> = {};
  rawQualityData.value.forEach((item: any) => {
    const groupId = item.materialGroupId || '未知群组';
    const groupName = item.materialGroupName || '未知群组';
    if (!groupRateMap[groupId]) {
      groupRateMap[groupId] = { sum: 0, count: 0, name: groupName };
    }
    groupRateMap[groupId].sum += item.qualifiedPercentage;
    groupRateMap[groupId].count += 1;
  });

  const groupData = Object.values(groupRateMap)
    .map(group => ({
      name: group.name,
      rate: (group.sum / group.count).toFixed(1)
    }))
    .sort((a, b) => Number(b.rate) - Number(a.rate))
    .slice(0, 8);

  groupChartInstance.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: '{b}: {c}%' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'value', min: 0, max: 100, axisLabel: { formatter: '{value}%' } },
    yAxis: { type: 'category', data: groupData.map(item => item.name), inverse: true },
    series: [{
      name: '平均合格率',
      type: 'bar',
      data: groupData.map(item => item.rate),
      itemStyle: {
        color: (params: any) => getRateColor(Number(params.value))
      },
      label: { show: true, position: 'right', formatter: '{c}%' }
    }]
  });
};

// 渲染质检人员工作量图表
const renderWorkloadChart = () => {
  if (!workloadChartInstance) return;

  const workloadMap: Record<string, number> = {};
  rawQualityData.value.forEach((item: any) => {
    const inspector = item.inspector || '未知人员';
    workloadMap[inspector] = (workloadMap[inspector] || 0) + 1;
  });

  const workloadData = Object.entries(workloadMap)
    .map(([name, value]) => ({ name, value }))
    .sort((a, b) => b.value - a.value);

  workloadChartInstance.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0, left: 'center' },
    series: [{
      name: '质检次数',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
      label: { show: false, position: 'center' },
      emphasis: {
        label: { show: true, fontSize: 16, fontWeight: 'bold' }
      },
      labelLine: { show: false },
      data: workloadData
    }]
  });
};

// 导出统计数据
const handleExport = async (type: 'current' | 'all') => {
  const loading = ElLoading.service({ text: '导出中...' });
  try {
    let exportData = [...rawQualityData.value];
    
    // 若导出全部，重新获取未筛选数据
    if (type === 'all') {
      const response = await axios.get('/api/QualityInspection/QualityInspectionQuery', {
        params: { Index: 1, Size: 9999 }
      });
      if (response.data.code === 200) {
        exportData = response.data.data.totalPage.map((item: any) => ({
          ...item,
          qualifiedPercentage: item.inspectedQuantity 
            ? (item.qualifiedQuantity / item.inspectedQuantity) * 100 
            : 0,
          inspectionDate: moment(item.inspectionTime).format('YYYY-MM-DD')
        }));
      }
    }

    // 格式化导出数据
    const formattedData = [
      { title: '=== 质检统计报表 ===', col2: '', col3: '', col4: '', col5: '', col6: '', col7: '', col8: '', col9: '', col10: '' },
      { 
        统计项: '总质检次数', 数值: stats.totalCount,
        统计项2: '平均合格率', 数值2: `${stats.averageRate.toFixed(1)}%`,
        col5: '', col6: '', col7: '', col8: '', col9: '', col10: ''
      },
      { 
        统计项: '不合格记录数', 数值: stats.unqualifiedCount,
        统计项2: '不合格占比', 数值2: `${stats.unqualifiedRatio.toFixed(1)}%`,
        col5: '', col6: '', col7: '', col8: '', col9: '', col10: ''
      },
      { title: '=== 明细数据 ===', col2: '', col3: '', col4: '', col5: '', col6: '', col7: '', col8: '', col9: '', col10: '' },
      {
        质检编号: '质检编号', 工单编号: '生产工单编号', 工单名称: '生产工单名称',
        物料群组: '物料群组名称', 检验数量: '检验数量', 合格数量: '合格数量',
        不合格数量: '不合格数量', 合格率: '合格百分比(%)', 质检人员: '质检人员',
        质检时间: '质检时间'
      },
      ...exportData.map((item: any) => ({
        质检编号: item.inspectionNumber,
        工单编号: item.produceCode,
        工单名称: item.produceName,
        物料群组: item.materialGroupName || '未知',
        检验数量: item.inspectedQuantity,
        合格数量: item.qualifiedQuantity,
        不合格数量: item.unqualifiedQuantity,
        合格率: item.qualifiedPercentage.toFixed(1),
        质检人员: item.inspector || '未知',
        质检时间: moment(item.inspectionTime).format('YYYY-MM-DD HH:mm:ss'),
        col10: ''
      }))
    ];

    // 生成Excel
    const worksheet = XLSX.utils.json_to_sheet(formattedData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, `质检统计_${type === 'current' ? '筛选' : '全部'}`);
    
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const fileName = `质检统计_${moment().format('YYYYMMDDHHmmss')}_${type === 'current' ? '筛选数据' : '全部数据'}.xlsx`;
    saveAs(blob, fileName);

    ElMessage.success(`成功导出 ${exportData.length} 条记录`);
  } catch (error) {
    ElMessage.error(`导出失败: ${(error as Error).message || '未知错误'}`);
    console.error(error);
  } finally {
    loading.close();
  }
};

// 页面生命周期
onMounted(() => {
  fetchAndAnalyzeData();
});

onBeforeUnmount(() => {
  destroyCharts();
});

// 监听窗口大小变化，重绘图表
watch(() => window.innerWidth, () => {
  nextTick(() => {
    if (trendChartInstance) trendChartInstance.resize();
    if (groupChartInstance) groupChartInstance.resize();
    if (workloadChartInstance) workloadChartInstance.resize();
  });
});
</script>

<style scoped>
.analysis-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.filter-card {
  margin-bottom: 16px;
  padding: 16px;
}
.stat-card-group {
  margin-bottom: 16px;
}
.stat-card {
  padding: 16px;
  text-align: center;
}
.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}
.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #333;
}
.chart-group {
  margin-bottom: 16px;
}
.chart-header {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}
.chart-container {
  width: 100%;
  height: 300px;
  margin-top: 8px;
}
.chart-dom {
  width: 100%;
  height: 100%;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .el-col {
    width: 100% !important;
    margin-bottom: 16px;
  }
}
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  .filter-card .el-form {
    flex-direction: column;
    align-items: flex-start !important;
  }
  .filter-card .el-form-item {
    width: 100% !important;
    margin-bottom: 8px;
  }
}
</style>
    